<template>
  <yj-main class="signature">
    <vcom-panel class="com-white">
      <div class="sys-box">
        <div class="sys-left">
          <p class="sys-p">
            <span>标签关联状态</span>
            <span class="el-icon-edit-outline sys-edit" @click="form.editshow = !form.editshow"></span>
          </p>
          <div class="sys-tag" v-if="timeValue===0">
            <div class="sys-kong">暂无标签关联</div>
          </div>
          <div class="tree-do" v-if="timeValue>0">
            <div v-if="form.isTreeShow">
            <yj-tree
            :data="form.treeData"
            ref="treeDom"
            default-expand-all
            node-key="tagEnumCode"
            :render-content="renderContent"
            highlight-current
            :expand-on-click-node="false"
            :class="form.treeAddChiledOne.tagEnumCode ? 'tree-dom' : 'tree-kong'"
            :props="{
              children: 'childrenDTOList',
              label: 'tagEnumName',
              id: 'tagEnumCode'
            }"
            ></yj-tree>
            </div>
          </div>
        </div>
        <div class="sys-right">
          <vcom-form v-model="form" :items="formItems" ref="form" labelWidth="110px">
            <vcom-form-item class="operationBtn">
              <span v-if="isShowInit">
                <vcom-button type="primary" @click="handleAdd" v-if="timeValue <= 1">确 定</vcom-button>
                <vcom-button type="primary" @click="falsehandleAdd" v-if="timeValue > 1">确 定</vcom-button>
              </span>
              <span v-else>
                <vcom-button type="primary" @click="handleAdd">确 定</vcom-button>
              </span>
              <vcom-button @click="goback" v-if="timeValue===0">取 消</vcom-button>
              <vcom-button @click="goNextBack" v-if="timeValue>0">返回上一级</vcom-button>
            </vcom-form-item>
          </vcom-form>
        </div>
      </div>
    </vcom-panel>
  </yj-main>
</template>

<script>
import form from '@/common/mixins/form.js';
import tagDialog from '../perTpl/tagDialog';
import { tagServe, temServe } from '@/api';
import { clone } from '@/utils/array.js';
export default {
  mixins: [form, tagDialog],
  data () {
    return {
      searchData: { // 标签弹框 分页
        name: '',
        pageSize: 10,
        pageNum: 1,
        ids: ''
      },
      cotyform: {},
      form: {
        isTreeShow: true,
        editshow: false, // 树上的删除添加
        name: '', // 模板名称
        rangeDTOList: [], // 使用范围
        templateTagLevelDTOList: [], // 系统模板树
        selectDialogObj: {}, // 标签对象
        showTag: '请选择标签',
        isShowTOList: true,
        optionsAll: [], // 标签值数据
        optionsBackData: [], // 标签值 回显
        treeData: [], // 树数据
        chooseAddFather: [], // 要添加到的父集
        treeAddChiledOne: {}
      },
      cascaprops: {
        value: 'tagEnumCode',
        label: 'tagEnumName',
        children: 'childrenDTOList'
      },
      cascaderselect: '',
      editid: '',
      defualtProps: {
        value: 'tagEnumCode',
        label: 'tagEnumName'
      },
      copyformItems_: [
        {
          label: '关联标签',
          field: 'transiTag',
          render: (h, row, value) => {
            return <div>{ <div class="tagshowsty" onClick={ () => { this.handleCopyShowTag(); } }>{this.form.showTag}</div>}</div>;
          }
        },
        {
          label: '关联标签值',
          field: 'transiTagVal',
          render: (h, row, value) => {
            return <div>
              <select-custom
                tagValue={this.form.selectDialogObj}
                options={ this.form.optionsAll }
                defualtProps={ this.defualtProps }
                optionsBackData={this.form.optionsBackData}
                onGetVlaue={ (val) => { this.getVlaue(val); }} // 关联层级 按钮
              ></select-custom>
            </div>;
          }
        }
      ],
      formItems_: [
        {
          label: '模板名称',
          field: 'name',
          placeholder: '请输入1-20字符集模板名称',
          width: '420px',
          required: true,
          maxlength: 20,
          showWordLimit: true
        },
        {
          label: '使用范围',
          field: 'rangeDTOList',
          required: true,
          type: 'checkbox',
          configCode: 'template_range'
        },
        {
          label: '组合标签',
          field: 'templateTagLevelDTOList',
          required: true,
          render: (h, row, value) => {
            return <div>
              { this.form.isShowTOList &&
              <div>
                { this.timeValue % 2 === 1 && <select-custom
                  tagValue={this.form.selectDialogObj}
                  options={ this.form.optionsAll }
                  defualtProps={ this.defualtProps }
                  optionsBackData={this.form.optionsBackData}
                  onGetVlaue={ (val) => { this.getVlaue(val); }} // 关联层级 按钮
                ></select-custom> }
                { this.timeValue % 2 === 0 && <div class="tagshowsty" onClick={ () => { this.handleCopyShowTag(); } }>请选择标签</div> }
              </div>
              }
              {
                !this.form.isShowTOList &&
                <yj-cascader
                  v-model={this.cascaderselect}
                  options={ this.form.treeData }
                  props={ this.cascaprops }
                ></yj-cascader>
              }
            </div>;
          }
        }
      ],
      radioAry: [],
      total: '',
      radioName: '', // 弹框中的标签id
      timePath: [], // 时间轨迹
      isShowInit: true
    };
  },
  computed: {
    formItems () {
      let ary = [];
      if (this.isShowInit) {
        if (this.timeValue > 1) {
          ary = this.copyformItems_;
        } else {
          ary = this.formItems_;
        }
      } else {
        ary = this.formItems_;
      }
      return ary;
    },
    timeValue () {
      return this.timePath.length;
    }
  },
  watch: {
    'timeValue' (val) {
      // let obj = this.timePath[this.timePath.length - 1] || {};
      // console.log(this.timePath);
      // if (this.timePath.length % 2 === 0) {
      //   this.form.optionsAll = [];
      //   this.form.selectDialogObj = {};
      // }
    }
  },
  methods: {
    handleCopyShowTag () {
      if (this.form.treeAddChiledOne.tagEnumCode && this.form.treeData) {
        let resultAllId = [];
        resultAllId = this.getCurrentFatherId(this.form.treeData, this.form.treeAddChiledOne.tagEnumCode, 'tagId');
        this.searchData.ids = resultAllId.length > 0 ? resultAllId.join(',') : '';
        this.getRadioData(this.searchData); // 标签更新 带过滤
      } else {
        if (this.form.treeData) {
          let resultAllId = [];
          this.getFatherId(this.form.treeData, resultAllId);
          this.searchData.ids = resultAllId.length > 0 ? resultAllId.join(',') : '';
          this.getRadioData(this.searchData); // 标签更新 带过滤
        }
      }
      this.handleShowTag();
    },
    goback () {
      this.$router.go(-1);
    },
    renderContent (h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{node.label}</span>
          { this.form.editshow &&
          <span>
            <span class="el-icon-close el-iconright" on-click={ () => this.deleteTree(node, data) }></span>
            <span class="el-icon-plus" on-click={ () => this.append(data) }></span>
          </span>
          }
        </span>);
    },
    // 获取树形结构的所有指定值

    getFatherName (data, resultary, getname) {
      let i;
      console.log(i);
      for (i in data) {
        if (!resultary.includes(data[getname])) {
          resultary.push(data[getname]);
        }
        if (data.childrenDTOList && data.childrenDTOList.length > 0) {
          this.getFatherId(data.childrenDTOList, resultary, getname);
        }
      }
    },
    // 删除树节点
    async deleteTree (node, data) {
      // console.log(node, data);
      if (this.editid) { // 修改时候 删除需要调用接口
        let resultary = [];
        this.getFatherName(data, resultary, 'id');
        let obj = {};
        obj.ids = resultary.join(',');
        obj.sysTemplateId = this.editid;
        let res = await tagServe.delTemplateTagLevel(obj);
        if (res.code === '200') {
          this.$message.success('删除成功');
        } else {
          this.$message.error(res.message);
        }
      }
      let parent = node.parent;
      const children = parent.data.childrenDTOList || parent.data;
      let index = children.findIndex(d => d.tagEnumCode === data.tagEnumCode);
      children.splice(index, 1);
    },
    append (data) {
      this.timePath.push(this.form);

      this.form.treeAddChiledOne = data;
    },

    // 返回上一次操作
    goNextBack () {
      this.timePath.pop();
      this.timePath.pop();
      // if (this.timePath.length === 3) {
      //     this.timePath.pop();
      // }
      if (this.timePath.length === 0) {
        this.form = this.cotyform;
      } else {
        let obj = this.timePath[this.timePath.length - 1] || {};
        const copyobj = clone(obj);
        copyobj.treeAddChiledOne = {};
        Object.keys(this.form).forEach(index => {
          copyobj[index] && (this.form[index] = copyobj[index]);
        });
        this.isShowInit = true;
      }
      this.form.isTreeShow = false;
      this.$nextTick(() => {
        this.form.isTreeShow = true;
      });
    },
    /**
     * @ 给树上添加等级字段
     * obj 树结构
     * inx 从几开始
     */
    addinx (obj, inx) {
      obj.forEach((item, i) => {
        // item.level = inx;
        this.$set(item, 'level', inx);
        if (item.childrenDTOList && item.childrenDTOList.length > 0) {
          inx++;
          this.addinx(item.childrenDTOList, inx);
          inx--;
        }
      });
    },
    // 关联下级
    linkTree (originary, level, val) {
      originary.forEach((item, i) => {
        if (item.childrenDTOList && item.childrenDTOList.length > 0) {
          this.linkTree(item.childrenDTOList, level, val);
        }
        if (item.level) {
          if (item.level === level) {
            this.addLinkTree(item, level + 1, val);
          }
        }
      });
    },
    // 添加节点
    addLinkTree (obj, level, val) {
      val && val.map(item => {
        if (!obj.childrenDTOList) {
          this.$set(obj, 'childrenDTOList', []);
        }
        item.level = level;
        obj.childrenDTOList.push({ ...item });
      });
      this.$forceUpdate();
    },
    // 关联层级
    getVlaue (val) {
      this.form.treeData && this.addinx(this.form.treeData, 1);
      if (this.form.treeAddChiledOne.tagEnumCode) { // 树上点击添加
        val && val.forEach(item => {
          if (!this.form.treeAddChiledOne.childrenDTOList) {
            this.$set(this.form.treeAddChiledOne, 'childrenDTOList', []);
          }
          this.form.treeAddChiledOne.childrenDTOList.push(item);
        });
      } else { // 右边添加
        if (this.form.chooseAddFather.length > 0) {
          this.linkTree(this.form.treeData, this.form.chooseAddFather[0].level, val);
          this.form.isTreeShow = true;
        } else {
          val && val.forEach(item => {
            this.$set(item, 'level', 1);
            this.form.treeData.push(item);
          });
        }
      }
      this.form.chooseAddFather = val; // 存入 父集
      let obj = clone(this.form);
      this.timePath.push(obj);

      this.radioName = '';
      this.form.showTag = '请选择标签';
      this.form.selectDialogObj = {};
      this.form.optionsAll = [];
      this.form.treeAddChiledOne = {};
    },
    // 获取当前点击这一层的所有父集id
    getCurrentFatherId (row, id, resulttype) {
      for (let i in row) {
        if (row[i].tagEnumCode === id) {
          return [row[i][resulttype]];
        }
        if (row[i].childrenDTOList && row[i].childrenDTOList.length > 0) {
          let ro = this.getCurrentFatherId(row[i].childrenDTOList, id, resulttype) || [];
          if (ro !== 'undefined') {
            return ro.concat(row[i][resulttype]);
          }
        }
      }
    },
    // 获取树上所有的标签id
    getFatherId (ary, resultary) {
      if (ary.length > 0) {
        ary.forEach(item => {
          if (!resultary.includes(item.tagId)) {
            resultary.push(item.tagId);
          }
          if (item.childrenDTOList && item.childrenDTOList.length > 0) {
            this.getFatherId(item.childrenDTOList, resultary);
          }
        });
      }
    },
    // 根据标签id查询标签值
    async handleTagValueSearch (id) {
      let res = await tagServe.getTagDetail({ id: id });
      if (res.code === '200') {
        let data = res.data || {};
        return data;
      }
    },
    // 标签弹框确定
    async handleSure (dialog) {
      if (!this.radioName) {
        dialog.distroy();
        return;
      }
      let ary = this.radioAry.filter(item => item.id === this.radioName);
      this.form.selectDialogObj = ary.length > 0 ? ary[0] : {};

      if (this.timeValue > 1) {
        this.form.showTag = this.form.selectDialogObj.name;
      }
      let tagArayObj = await this.handleTagValueSearch(this.form.selectDialogObj.id),
        tagselectAry = tagArayObj.tagEnumVoList.length > 0 && tagArayObj.tagEnumVoList.map(item => {
          return {
            id: '',
            pId: '',
            tagId: item.tagId,
            tagEnumCode: item.code,
            tagEnumName: item.name
          };
        });
      this.form.optionsAll = tagselectAry;
      let obj = clone(this.form);
      this.timePath.push(obj);
      dialog.distroy();
    },
    // 弹框搜索 type:1 过滤 文本 和 时间
    async getRadioData (obj) {
      let res = await tagServe.getTagListPageName({...obj, ...{type: 1}});
      if (res.code === '200') {
        let data = res.data || {};
        this.radioAry = data.content || [];
        this.total = data.total;
      }
    },
    // 使用范围的数据
    handleRangeData (ary, rangeDTOList, resultary) {
      ary.map(item => {
        rangeDTOList.map(k => {
          if (item.value === k) {
            resultary.push({
              itemCode: item.value,
              itemName: item.label
            });
          }
        });
      });
    },
    falsehandleAdd () {
      this.isShowInit = false;
      this.form.isShowTOList = false;
    },
    // submit 添加
    async handleAdd () {
      this.form.templateTagLevelDTOList = this.form.treeData;
      if (this.$refs.form.validator()) {
        let ary = [], resultary = [];
        ary = this.formItems.filter(item => item.field === 'rangeDTOList');
        this.handleRangeData(ary[0].options, this.form.rangeDTOList, resultary);
        let obj = {};
        obj.id = this.editid;
        obj.name = this.form.name;
        obj.type = 0;
        obj.rangeDTOList = resultary;
        obj.templateTagLevelDTOList = this.form.templateTagLevelDTOList;
        let res = await temServe.addOrUpdaterSysTemplate(obj);
        if (res.code === '200') {
          this.$message.success('添加成功');
          this.$router.push({ path: `/sysTpl` });
        }
      }
    },
    async getbackData (id) {
      let obj = {};
      obj.id = id;
      obj.type = 0;
      this.editid = id;
      let res = await temServe.getTemplateDetail(obj);
      if (res.code === '200') {
        let data = res.data || {};
        this.form.name = data.name;
        let ary = data.rangeDTOList.length > 0 ? data.rangeDTOList.map(item => item.itemCode) : [];
        this.form.rangeDTOList = ary;
        this.form.treeData = data.templateTagLevelDTOList;
        this.timePath.push(this.cotyform);
        this.form.isShowTOList = false;
      }
    }
  },
  mounted () {
    this.cotyform = clone(this.form);
    this.getRadioData(this.searchData);
    this.loadFormItemsOptions(this.formItems);
  },
  created () {
    let backData = this.$route.query;
    if (backData.id) { // 修改
      this.getbackData(backData.id);
    }
  }
};
</script>

<style lang="scss">
.tree-kong .el-tree-node.is-current > .el-tree-node__content{
  background-color: #fff !important;
  color: #606266 !important;
}
.el-red{
  color: #f00;
  cursor: pointer;
}
.com-input{
  width: 200px;
  padding-right: 10px;
}
.my-radiochoose .el-radio{
  padding: 10px;
}
.custom-tree-node{
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.sys-edit{
  float: right;
  margin-right: 3%;
  color: #1890FF;
  cursor: pointer;
}
.el-iconright{
  padding-right: 10px;
}
.el-cascader-menu__list{
  // height: 40px;
}
.tagshowsty{
  box-sizing: border-box;
  padding: 0px 12px 0px 10px;
  border: 1px solid #D9D9D9;
  border-radius: 5px;
  color: #D9D9D9;
  display: inline-block;
  font-size: 14px;
  width: 222px;
}
</style>

<style lang="scss" scoped>
.sys-box{
  display: flex;
  .sys-left{
    width: 40%;
    border: 1px solid #D9D9D9;
    border-radius: 5px;
    margin-right: 5%;
    .sys-p{
      text-align: center;
      font-size: 16px;
      padding: 15px 0;
      background-color: #E8EAED;
    }
    .sys-tag{
      text-align: center;
      min-height: 400px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .tree-do{
      height: 400px;
      overflow: auto;
      box-sizing: border-box;
      padding: 20px;
    }
    .sys-kong{
      color: rgba(0,0,0,0.2);
      font-size: 16px;
    }
  }
  .sys-right{
    padding: 20px 0;
    .operationBtn{
      padding: 80px 0;
      margin-left: 102px;
    }
  }
}
</style>
